/**
 *
 * @description:首页、阅读全文
 * @author:junyong.hong
 * @createTime:2018/1/8
 * @version:1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
var express = require('express');
var router = express.Router();

var Category = require('../models/Category');
var Content = require('../models/Content');
var User = require('../models/User');

var data;
/**
 * 中间件：处理通用的数据
 */
router.use(function (req,res,next) {
    data = {
        userInfo:req.userInfo,
        categories:[]
    };

    /**
     * 分类的读取
     */
    Category.find().then(function (categories) {
        data.categories = categories;
        next();
    });
});

/**
 * 首页
 */
router.get('/',function (req,res,next) {


    // data = {
    //     // userInfo:req.userInfo,
    //     category:req.query.category ||  '',
    //     // categories:[],
    //
    //     count:0,
    //     page:Number(req.query.page ||  1),
    //     limit:2,
    //     pages:0
    // };

    data.category = req.query.category ||  '';
    data.count = 0;
    data.page = Number(req.query.page || 1);
    data.limit = 2;
    data.pages = 0;

    //查询条件
    var stringWhere = {};
    if(data.category){
        stringWhere.category = data.category
    }


    //读取所有的分类信息
    // Category.find().then(function (categories) {
    //
    //     data.categories = categories;
    //
    //     //返回到紧邻的then
    //     return Content.where(stringWhere).count();
    // })
    // .then(function (count) {
    Content.where(stringWhere).count().then(function (count) {

        // 总条数
        data.count = count;

        // 计算总页数
        data.pages = Math.ceil(data.count / data.limit);
        // 取值不能超过pages
        data.page = Math.min(data.page, data.pages);
        // 取值不能小于1
        data.page = Math.max(data.page ,1);

        var skip = (data.page - 1) * data.limit;//忽略条数

        //返回到紧邻的then
        return Content.where(stringWhere).find().limit(data.limit).skip(skip).populate(['category','user']).sort({
            addTime:-1
        });
    }).then(function (contents) {
        data.contents = contents;

        res.render('main/index',data);
    });
});

/**
 * 阅读全文
 */
router.get('/view',function (req,res) {
    var contentId = req.query.contentid || '';

    Content.findOne({
        _id:contentId
    }).then(function (content) {
        data.content = content;

        User.findOne({
            _id:content.user
        }).then(function (d) {
            data.author = d.username;   //作者的用户名

            content.views ++;
            content.save();

            res.render('main/view/view',data);
        });

    });
});

//返回数据
module.exports = router;